const router = require('koa-router')()
const md5 = require('blueimp-md5')
const DB = require('../db')
const actualGmoney = require('../utils/actualGmoney')

router.prefix('/mall')

/**商家上架商品 */
router.post('/sell', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { goodsName, cateTag, goodsImages, brand, oldDegree, price, isAcceptCutPrice, billImg, goodsDetails } = ctx.request.body
  if (!goodsName.trim() || !cateTag || goodsImages.length === 0 || !brand || !oldDegree || !price || !billImg || !goodsDetails) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }

  const r = await DB.find('users', { userName })
  if (r.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }

  await DB.add('mall', {
    goodsId: md5(`${userName}_${Date.now()}`), // 商品唯一Id
    userName: userName, // 商家用户名  
    nick: r[0].nick, // 商家昵称
    goodsName: goodsName, // 商品名称,
    goodsCate: cateTag, // 商品分类
    brand: brand, // 商品品牌
    oldDegree: oldDegree, // 商品成色 x成新
    goodsImages: goodsImages, // 商品图片列表[]
    price: price, // 商品价格
    isAcceptCutPrice: isAcceptCutPrice, // 商家是否接受议价砍价
    billImg: billImg, // 发票图片或质检图片
    goodsDetails: goodsDetails, // 商品详情
    onSaleDate: Date.now(), // 商品上架日期
    offSaleDate: 0, // 商品下架日期(商品没卖出去，商家停止出售了)，默认为0
    sellEndDate: 0, // 商品成功出售的日期，默认为0
    goodsStatus: 1, // 商品当前销售状态 1--在售 2--已下架未售出 3--已售出
    shoppingCartList: [], // 该商品被哪些买家加入了购物车
    orderId: '', // 交易订单号
    isSHowInMyGoods: true, // 是否在我的商品列表中显示，默认为true， 设置为false时，表示被卖家从我的商品列表中删除
    buyer: '', // 买家的userName
  })

  ctx.body = {
    code: '0000',
    msg: '商品上架成功',
    data: true
  }
})

/**获取我的商品 */
router.get('/mygoods', async (ctx, next) => {
  const userName = ctx.query.userName || ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const r1 = await DB.findInNE('mall', { userName }, 'isSHowInMyGoods', false)
  ctx.body = {
    code: '0000',
    msg: 'success',
    data: r1
  }
})

/**调整商品状态 
 * 点击上架 传参type为1 
 * 点击下架 传参type为2
 * 点击删除 传参type为4
 */
router.post('/changeGoodsState', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { goodsId, type } = ctx.request.body
  if (!goodsId || !type) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  switch (type) {
    case 1:
      await DB.updateValue('mall', { goodsId }, { goodsStatus: 1, onSaleDate: Date.now() })
      break
    case 2:
      await DB.updateValue('mall', { goodsId }, { goodsStatus: 2, offSaleDate: Date.now() })
      break
    case 4:
      await DB.updateValue('mall', { goodsId }, { isSHowInMyGoods: false })
      break
  }
  ctx.body = {
    code: '0000',
    msg: '操作成功',
    data: true
  }
})

/**获取商城首页商品分类列表 */
router.get('/getCateList', async (ctx, next) => {
  const r1 = await DB.find('mall', { goodsStatus: 1 })
  ctx.body = {
    code: '0000',
    msg: '查询成功',
    data: r1
  }
})

/**根据goodsId获取单个商品信息 */
router.get('/singleGoods', async (ctx, next) => {
  const { goodsId } = ctx.query
  if (!goodsId) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const r1 = await DB.find('mall', { goodsId })
  if (r1.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }
  ctx.body = {
    code: '0000',
    msg: '查询成功',
    data: r1[0]
  }
})

/**购物付款 */
router.post('/paygmoney', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { sellerUserName, goodsId, price } = ctx.request.body
  if (!sellerUserName || !goodsId || !price) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  if (sellerUserName === userName) {
    ctx.body = {
      code: '0018',
      msg: '不能购买自己的宝贝',
      data: false
    }
    return
  }
  const r1 = await DB.find('mall', { goodsId })
  if (r1[0].goodsStatus === 2) {
    ctx.body = {
      code: '0014',
      msg: '该商品已下架',
      data: false
    }
    return
  }
  if (r1[0].goodsStatus === 3) {
    ctx.body = {
      code: '0015',
      msg: '该商品已售出',
      data: false
    }
    return
  }
  if (parseFloat(price) !== r1[0].price) {
    ctx.body = {
      code: '0016',
      msg: '该商品价格已变更',
      data: false
    }
    return
  }
  const r2 = await DB.find('users', { userName })
  if (r2[0].gMoney < r1[0].price) {
    ctx.body = {
      code: '0017',
      msg: 'G币余额不足',
      data: false
    }
    return
  }
  await DB.updateValue('users', { userName }, {
    gMoney: r2[0].gMoney - r1[0].price
  })
  const r3 = await DB.find('users', { userName: sellerUserName })
  await DB.updateValue('users', { userName: sellerUserName }, {
    gMoney: r3[0].gMoney + actualGmoney(r1[0].price)
  })
  await DB.updateValue('mall', { goodsId }, {
    sellEndDate: Date.now(),
    goodsStatus: 3,
    orderId: `B${Date.now()}`,
    buyer: userName
  })
  await DB.updateDeep('users', { userName }, {
    consumeDetails: {
      consumeDate: Date.now(), // 消费日期
      orderId: `B${Date.now()}`, // 消费订单号
      consumeName: r1[0].goodsName, // 消费商品名称
      consumeAmount: r1[0].price, // 消费G币数量
      consumeChannel: '淘宝贝', // 消费渠道
      consumeStatus: '已支付', // 订单状态
    }
  })
  ctx.body = {
    code: '0000',
    msg: '购买成功',
    data: true
  }
})

/**加入购物车 */
router.post('/addcart', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { sellerUserName, goodsId } = ctx.request.body
  if (!goodsId) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  if (sellerUserName === userName) {
    ctx.body = {
      code: '0019',
      msg: '不能收藏自己的宝贝',
      data: false
    }
    return
  }
  const r1 = await DB.find('mall', { goodsId })
  if (r1[0].shoppingCartList.includes(userName)) {
    ctx.body = {
      code: '0020',
      msg: '不能重复收藏',
      data: false
    }
    return
  }
  if (r1[0].goodsStatus === 2) {
    ctx.body = {
      code: '0014',
      msg: '该商品已下架',
      data: false
    }
    return
  }
  if (r1[0].goodsStatus === 3) {
    ctx.body = {
      code: '0015',
      msg: '该商品已售出',
      data: false
    }
    return
  }
  await DB.updateDeep('mall', { goodsId }, { shoppingCartList: userName })
  ctx.body = {
    code: '0000',
    msg: '已加入购物车',
    data: true
  }
})

module.exports = router